package com.ddxz.tools.license.listener;


import com.ddxz.tools.license.common.DdxzLicenseException;
import com.ddxz.tools.license.common.LicenseCheck;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.event.SpringApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.Ordered;

import static com.ddxz.tools.license.LicenseError.INVALID_LICENSE;

/**
 * @author 朱宗刚
 * @version 1.0.0
 * @date 2020/5/20
 */

public class LicenseListener implements ApplicationListener<SpringApplicationEvent>, Ordered {
    private final String license;
    private final String companyName;
    private final String applicationName;

    @Override
    public void onApplicationEvent(SpringApplicationEvent event) {
        LicenseCheck.installLicense(license, companyName, applicationName);

        if(!LicenseCheck.checkLicense()) {
            throw new DdxzLicenseException(INVALID_LICENSE);
        }
        logger.info("license check passed.");
    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }

    public LicenseListener(String license, String companyName, String applicationName) {
        this.license = license;
        this.companyName = companyName;
        this.applicationName = applicationName;
    }

    private static final Logger logger = LoggerFactory.getLogger(LicenseListener.class);
}
